<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          title="地下空洞隐患预警信息"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #bclassify="scope">
            {{ getDictValue(scope.row.bclassify, bClassifyOptions) }}
          </template>
          <template #sclassify="scope">
            {{ getDictValue(scope.row.sclassify, sClassifyOptions) }}
          </template>
          <template #category="scope">
            {{ getDictValue(scope.row.category, categoryOptions) }}
          </template>
          <template #grade="scope">
            {{ getDictValue(scope.row.grade, gradeOptions) }}
          </template>
          <template #state="scope">
            {{getDictValue(scope.row.state, stateOptions)}}
          </template>
          <template #fromType="scope">
            {{getDictValue(scope.row.fromType, fromTypeOptions)}}
          </template>
          <template #superviseState="scope">
            {{getDictValue(scope.row.superviseState, superviseStateOptions)}}
          </template>
          <template #operation="scope">
            <a v-hasPermission="['riskHazard:add']" class="table-btn-edit table-operation"
               @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
            <span v-if="scope.row.superviseOrderNum==null||scope.row.superviseOrderNum==''" >
                          <a v-hasPermission="['riskHazard:orderPush']" class="table-btn-view table-operation"
                             @click="supervise(scope.row)">{{$t('table.urge')}}</a>
                        </span>
            <a v-hasPermission="['riskHazard:add']" class="table-btn-view table-operation"
               @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
            <a v-hasPermission="['riskHazard:delete']" class="table-btn-delete table-operation"
               @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
          </template>
        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>
    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :openType="detailOpenType"
                  :superviseOrderNum="curSuperviseOrderNum"
                  :id="detailId"
                  :title="detailTitle"
    ></detailDialog>
    <tableImportDialog
      ref="importDialog"
      :dialog-visible.sync="importDialog.isVisible"
      :title="importDialog.title"
      :template-list="importTemplateList"
      :uploadOptions="uploadOptions"
    />
  </div>
</template>

<script>
import {
  riskHazardPage,
  riskHazardExport,
  riskHazardDelete,
  orderPush
} from '@/api/risk/riskHazard'
import SearchForm from '@/components/searchForm/index'
import ButtonForm from '@/components/ButtonForm/index'
import VTable from '@/components/VTable/index'
import Pagination from '@/components/Pagination/index'
import detailDialog from './detail.vue'
import tableImportDialog from '@/components/TableImportDialog/tableImportDialog'

export default {
  components: {
    VTable, Pagination, detailDialog, SearchForm, ButtonForm, tableImportDialog
  },
  data() {
    return {
      importDialog: {
        isVisible: false,
        title: '风险隐患上报'
      },
      importTemplateList: [
        {
          label: '下载导入模板',
          url: '/risk/riskHazard/template',
          downloadFileName: '风险隐患上报.xlsx',
          // clickFn: this.downloadTemplate, //选填项，点击下载按钮时触发，如果想自己手动实现下载，可在这里定义方法，否则使用默认的下载方法
        },
      ],
      uploadOptions: {
        accept: '.xlsx', //限制文件格式，多个用逗号隔开如：'.xlsx,.png'
        uploadTextTip: '请上传excel文件,以.xlsx为后缀',
        url: '/risk/riskHazard/import',
        // uploadFn: this.handleUpload, //选填项，点击确认时触发上传，如果想自己手动实现上传，可在这里定义方法，否则使用默认的上传方法
        successFn: this.handleUploadSuccess, //选填项，上传成功后触发
      },

      tableColumns: [
        // {
        //   prop: 'flagCode',
        //   label: '标识码',
        //   minWidth: '100',
        //   slotname: 'flagCode',
        //   options: {}
        // },
        {
          prop: 'name',
          label: '隐患名称',
          minWidth: '150',
          slotname: 'name',
          options: {}
        },
        // {
        //   prop: 'bclassify',
        //   label: '风险隐患大类',
        //   minWidth: '150',
        //   slotname: 'bclassify',
        //   options: {}
        // },
        // {
        //   prop: 'sclassify',
        //   label: '风险隐患细类',
        //   minWidth: '150',
        //   slotname: 'sclassify',
        //   options: {}
        // },
        {
          prop: 'state',
          label: '隐患状态',
          minWidth: '150',
          slotname: 'state',
          options: {}
        },
        {
          prop: 'grade',
          label: '隐患等级',
          minWidth: '150',
          slotname: 'grade',
          options: {}
        },
        {
          prop: 'fromType',
          label: '隐患来源',
          minWidth: '150',
          slotname: 'fromType',
          options: {}
        },

        {
          prop: 'discoveryTime',
          label: '发现时间',
          minWidth: '150',
          slotname: 'discoveryTime',
          options: {}
        },

        {
          prop: 'address',
          label: '隐患地址',
          minWidth: '150',
          slotname: 'address',
          options: {}
        },


        {
          prop: 'finishTimeState',
          label: '是否按时处置',
          minWidth: '150',
          slotname: 'finishTimeState',
          options: {}
        },



        {
          prop: 'reportName',
          label: '上报人',
          minWidth: '150',
          slotname: 'reportName',
          options: {}
        },
        {
          prop: 'reportTime',
          label: '上报时间',
          minWidth: '150',
          slotname: 'reportTime',
          options: {}
        },
        {
          prop: 'superviseState',
          label: '督办状态',
          minWidth: '100',
          slotname: 'superviseState',
          options: {}
        },
        {
          prop: 'operation',
          label: '操作',
          width: '200',
          align: 'center',
          slotname: 'operation',
          overflow: false,
          fixed: 'right'
        }
      ],
      tableData: [],
      selection: [],
      loading: false,
      total: 1,
      pageNum: 1,
      pageSize: 10,
      detailOpenType: "add",
      detailDialogShow: false,
      curSuperviseOrderNum:"",
      detailId: "",
      detailTitle: "新增",
      dict: {},
      searchData: {
        form: {
          name: '',
          bclassify: '03',
          address: '',
          state: '',
        },
        options: [
          {
            title: '隐患名称',
            key: "name",
            type: "text",
          },

          {
            title: '隐患地址',
            key: "address",
            type: "text",
          },
          /*{
            title:'隐患大类',
            key: "bclassify",
            type: "select",
            multiple:false,
            option: {
              data: this.bClassifyOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "name", // 指定value对应data的字段
              },
            },
          },*/
          {
            title:'是否按时处置',
            key: "finishTimeState",
            type: "select",
            multiple:false,
            option: {
              data: this.finishTimeStateOptions,
              props: {
                key: "id", // 指定key对应data的字段
                label: "label", // 指定label对应data的字段
                value: "name", // 指定value对应data的字段
              },
            },
          },

        ]
      },
      buttonList: [
        {name: '新增', methods: 'handleAdd', type: 'primary', hasPremission:["riskHazard:add"]},
        //{name: '导入', methods: 'handleImport'},
        //{name: '导出', methods: 'handleExport'}
      ],
      tableMainHeight: 0,
      // 字典
      bClassifyOptions: [],
      bSlassifyOptions: [],
      categoryOptions: [],
      gradeOptions: [],
      superviseStateOptions:[],
      fromTypeOptions:[],

    }
  },
  watch: {
    // 字典

    'stateOptions':{
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t=>{
          if(t.key=='state'){
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },

    'fromTypeOptions':{
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t=>{
          if(t.key=='fromType'){
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },

    'bClassifyOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'bclassify') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },

    'sClassifyOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'sclassify') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },

    'categoryOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'category') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },

    'gradeOptions': {
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t => {
          if (t.key == 'grade') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'finishTimeStateOptions':{
      handler(newVal, oldVal) {
        this.searchData.options.forEach(t=>{
          if(t.key=='finishTimeState'){
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    handleDownload(data) {
      let fileName = "风险隐患上报导入模板.xlsx"
      return riskSourceTemplate(data, fileName)
    },
    handleUpload(file) {
      // console.log("file",file)
      const formData = new FormData()
      formData.append('file', file)
      //   formData.append('file', fileList[0].raw)
      //   console.log("formData,==",formData.get("file"))
      riskShelterImport(formData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('导入成功')
            this.search()
            this.importDialog.isVisible = false
          }
        })
        .finally(() => {
          this.$refs.importDialog.clearFileList()
        })
    },
    handleUploadSuccess() {
      this.search()
      this.importDialog.isVisible = false
    },
    handleClose() {
      this.importDialog.isVisible = false
    },

    getCheckBoxValue(value, option) {
      if (!value) {
        return
      }
      let temp = []
      let data = value.split(",")
      data.forEach(t => {
        let item = option.find(x => x.value == t)
        if (item != undefined) {
          temp.push(item.label)
        }
      })
      return temp.join(",")
    },
    getDictValue(value, option) {
      let item = option.find(t => t.value == value)
      if (item != undefined) {
        return item.label
      }
      return value
    },
    editClose() {
      this.detailDialogShow = false
    },
    editSuccess() {
      this.search()
      this.detailDialogShow = false
    },
    search() {
      this.fetch({
        ...this.searchData.form,
      })
    },
    fetch(params = {}) {
      params.pageSize = this.pageSize
      params.pageNum = this.pageNum
      this.loading = true
      params.bclassify = '03'
      // 添加具体道路塌陷类型
      params.sclassify = '008'
      riskHazardPage(params).then(res => {
        if (res.code == 200) {
          this.total = res.data.total
          this.tableData = res.data.rows
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      }).finally(final => {
        this.loading = false
      })
    },
    // 重置搜索条件
    resetSearchData() {
      this.searchData.form = {
        name: '',
        bclassify: '03',
        address: '',
        state: '',
      }
    },

    // 触发按钮区域按钮方法
    clickButton(methods) {
      this[methods]()
    },
    handleAdd() {
      this.detailOpenType = "add"
      this.detailTitle = "新增"
      this.detailDialogShow = true
    },
    handleEdit(row) {
      this.detailId = row.id
      this.detailOpenType = "edit"
      this.detailTitle = "编辑"
      this.detailDialogShow = true
    },
    handleDetail(row){
      this.detailId = row.id
      this.detailOpenType = "detail"
      this.detailTitle="详情"
      this.curSuperviseOrderNum= row.superviseOrderNum
      this.detailDialogShow = true
    },
    supervise(row){
      this.$confirm('确定督办？', this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        var param = {};
        param.orderNum = row.id;
        var backData ={};
        backData.type='1';
        param.backData = JSON.stringify(backData);
        orderPush(param).then(res=>{
          if(res.code==200){
            this.$message({
              message: '督办提交成功',
              type: 'success'
            })
            this.search()
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      })
    },
    handleExport() {
      let params = {
        ...this.searchData.form
      }
      riskHazardExport(params, `风险隐患上报_${new Date().getTime()}.xlsx`);
    },
    handleImport() {
      console.log("等待处理")
      this.importDialog.isVisible = true
    },


    closeDialog() {
      this.detailDialogShow = false
    },

    singleDelete(row) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        riskHazardDelete(row.id).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.deleteSuccess'),
              type: 'success'
            })
            this.search()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final => {
          this.loading = false
        })
      })
    }
  },
  activated() {
    this.fetch()
  },
  created() {
    this.fetch()
    // 获取字典值
    this.bClassifyOptions = []
    this.$commonJs.filterDataDict("hazardBClassify", this.bClassifyOptions)

    this.sClassifyOptions = []
    this.$commonJs.filterDataDict("hazardSClassify", this.sClassifyOptions)

    this.categoryOptions = []
    this.$commonJs.filterDataDict("hazardCategory", this.categoryOptions)

    this.gradeOptions = []
    this.$commonJs.filterDataDict("patrolHazardLevel", this.gradeOptions)



    this.stateOptions = []
    this.$commonJs.filterDataDict("hazardDealState", this.stateOptions)

    this.fromTypeOptions = []
    this.$commonJs.filterDataDict("hazardFromType", this.fromTypeOptions)

    this.finishTimeStateOptions = [{"name":"1","label":"按时"},{"name":"2","label":"超时"}]

    this.superviseStateOptions = []
    this.$commonJs.filterDataDict("superviseState",this.superviseStateOptions )

  },
  mounted() {
    this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
  }
}
</script>

<style lang="scss" scoped>
.table-all {
  display: flex;
  flex-direction: column;
  height: 100%;

  .search-box {
    padding-bottom: 6px;
  }

  .table-box {
    padding-top: 10px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .table-main {
      flex: 1;
      overflow: auto;
    }

    .table-page {
      // padding-top: 10 px;
      // padding-bottom: 10 px;
    }

    ::v-deep .pagination-container {
      text-align: right;
    }

  }
}
</style>
